package gold.digger;

import gold.vo.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by fanzhenyu02 on 2020/6/27.
 * common problem solver template.
 */
public class LC450 {
    public long startExecuteTime = System.currentTimeMillis();


    class Solution {
        public TreeNode deleteNode(TreeNode root, int key) {
            return deleteNodeRecur(root, key);
        }

        public TreeNode deleteNodeRecur(TreeNode root, int key) {
            if (null == root) return null;

            if (root.val > key) {
                root.left = deleteNodeRecur(root.left, key);
                return root;
            }

            if (root.val < key) {
                root.right = deleteNodeRecur(root.right, key);
                return root;
            }

            // current root shall be deleted.
            if (null == root.right) return root.left;
            if (null == root.left) return root.right;

            // both child are not null, first use right to replace.
            adjustTree(root.right, root.left);
            return root.right;
        }

        public void adjustTree(TreeNode root, TreeNode targetChild) {
            if (null == root) return;
            if (root.val >= targetChild.val) {
                if (null == root.left) {
                    root.left = targetChild;
                    return;
                } else {
                    adjustTree(root.left, targetChild);
                    return;
                }
            } else {
                if (null == root.right) {
                    root.right = targetChild;
                    return;
                } else {
                    adjustTree(root.right, targetChild);
                    return;
                }
            }
        }

    }

    public void run() {
        Solution solution = new Solution();
        TreeNode root = TreeNode.createTree("[5,3,6,2,4,null,7]");
        TreeNode afterRoot = solution.deleteNode(root, 3);
        System.out.println(afterRoot);
    }

    public static void main(String[] args) throws Exception {
        LC450 an = new LC450();
        an.run();

        System.out.println("\ncurrent solution total execute time: " + (System.currentTimeMillis() - an.startExecuteTime) + " ms.");
    }
}
